package com.lee.hystrix.controller;

import com.lee.hystrix.annotation.MyHystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <br/>
 *
 * @author liyuanchang
 * @version V1.0
 * @email liyuanchang@chinamobile.com
 * @date 2019/6/14 14:22
 */
@RestController
@EnableCircuitBreaker
public class HelloController {
    static final Logger logger = LoggerFactory.getLogger(HelloController.class);

    Random random = new Random();

    @HystrixCommand(fallbackMethod = "fallback")
    @RequestMapping("/test")
    public String test() {
        logger.info("into test method!");
        throw new RuntimeException();
    }

    @MyHystrixCommand(fallbackMethod = "fallback")
    @RequestMapping("/myAnnotation")
    public String myAnnotation() {
        logger.info("into myAnnotation method!");
        throw new RuntimeException();
    }

    @HystrixCommand(fallbackMethod = "fallback")
    @RequestMapping("/timeout")
    public String timeout() {
        logger.info("into timeout method!");
        sleep(random.nextInt(4), TimeUnit.SECONDS);
        return "success";
    }

    public String fallback() {
        return "fallback";
    }

    static void sleep(int timeout, TimeUnit timeUnit) {
        try {
            timeUnit.sleep(timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
